package com.framework.bdf4j.job.controller;

import static com.framework.bdf4j.comm.enums.ScaQuartzEnum.JOB_LOG_STATUS_FAIL;
import static com.framework.bdf4j.comm.enums.ScaQuartzEnum.JOB_STATUS_DEL;
import static com.framework.bdf4j.comm.enums.ScaQuartzEnum.JOB_STATUS_NOT_RUNNING;
import static com.framework.bdf4j.comm.enums.ScaQuartzEnum.JOB_STATUS_RELEASE;
import static com.framework.bdf4j.comm.enums.ScaQuartzEnum.JOB_STATUS_RUNNING;

import java.util.Date;

import org.quartz.Scheduler;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.bdf4j.annotations.SysLog;
import com.framework.bdf4j.comm.persist.PageDomain;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.comm.util.StringUtils;
import com.framework.bdf4j.comm.util.job.CronUtils;
import com.framework.bdf4j.comm.util.job.TaskUtil;
import com.framework.bdf4j.comm.web.WebUtil;
import com.framework.bdf4j.job.entity.SysJob;
import com.framework.bdf4j.job.service.SysJobService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;

/**
 * 定时任务管理
 */
@Controller
@AllArgsConstructor
@RequestMapping("/admin/job")
@Api(value = "job", tags = "定时任务")
public class SysJobController {
    private final SysJobService sysJobService;
    private final TaskUtil taskUtil;
    private final Scheduler scheduler;

    // 跳转到角色列表页
    @GetMapping("/index")
    public String goJob() {
        return "monitor/job/jobList";
    }

    /**
     * 定时任务分页查询
     *
     * @param page
     *            分页对象
     * @param sysJob
     *            定时任务调度表
     * @return
     */
    @GetMapping("/page")
    @ResponseBody
    @ApiOperation(value = "分页定时业务查询")
    public R getSysJobPage(Page page, PageDomain domain, SysJob sysJob) {
        OrderItem orderitem = StringUtils.getOrderItem(domain);
        if (orderitem != null) {
            page.addOrder(orderitem);
        }
        return R.ok(sysJobService.page(page, Wrappers.query(sysJob)));
    }

    // 跳转到任务编辑页
    @GetMapping("/goEditJob")
    public String goEditJob(@RequestParam(required = false) String id, @RequestParam String oper, Model model) {
        SysJob job = new SysJob();
        if (!"add".equals(oper)) {
            job = sysJobService.getById(Integer.parseInt(id));
        }
        model.addAttribute("viewobject", job);
        model.addAttribute("oper", oper);
        return "monitor/job/jobEdit";
    }

    /**
     * 校验cron表达式是否有效
     */
    @PostMapping("/checkCronExpressionIsValid")
    @ResponseBody
    public boolean checkCronExpressionIsValid(SysJob job) {
        return CronUtils.isValid(job.getCronExpression());
    }

    /**
     * 新增定时任务
     *
     * @param sysJob
     *            定时任务调度表
     * @return R
     */
    @SysLog("新增定时任务")
    @PostMapping
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('job_sys_job_add')")
    @ApiOperation(value = "新增定时任务")
    public R save(SysJob sysJob) {
        sysJob.setJobStatus(JOB_STATUS_RELEASE.getType());
        sysJob.setCreateBy(WebUtil.getHttpCurrentUserName());
        return R.ok(sysJobService.save(sysJob));
    }

    /**
     * 修改定时任务
     *
     * @param sysJob
     *            定时任务调度表
     * @return R
     */
    @SysLog("修改定时任务")
    @PutMapping
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('job_sys_job_edit')")
    @ApiOperation(value = "修改定时任务")
    public R updateById(SysJob sysJob) {
        sysJob.setUpdateBy(WebUtil.getHttpCurrentUserName());
        SysJob querySysJob = this.sysJobService.getById(sysJob.getJobId());
        if (JOB_STATUS_NOT_RUNNING.getType().equals(querySysJob.getJobStatus())) {
            this.taskUtil.addOrUpateJob(sysJob, scheduler);
            sysJob.setUpdateTime(new Date());
            sysJobService.updateById(sysJob);
        } else if (JOB_STATUS_RELEASE.getType().equals(querySysJob.getJobStatus())) {
        	sysJob.setUpdateTime(new Date());
            sysJobService.updateById(sysJob);
        }
        return R.ok();
    }

    /**
     * 通过id删除定时任务
     *
     * @param id
     *            id
     * @return R
     */
    @SysLog("删除定时任务")
    @DeleteMapping("/{id}")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('job_sys_job_del')")
    @ApiOperation(value = "唯一标识查询定时任务，暂停任务才能删除")
    public R removeById(@PathVariable Integer id) {
        SysJob querySysJob = this.sysJobService.getById(id);
        if (JOB_STATUS_NOT_RUNNING.getType().equals(querySysJob.getJobStatus())) {
            this.taskUtil.removeJob(querySysJob, scheduler);
            this.sysJobService.removeById(id);
        } else if (JOB_STATUS_RELEASE.getType().equals(querySysJob.getJobStatus())) {
            this.sysJobService.removeById(id);
        }
        return R.ok();
    }

    /**
     * 暂停全部定时任务
     *
     * @return
     */
    @SysLog("暂停全部定时任务")
    @ResponseBody
    @PostMapping("/shutdown-jobs")
    @PreAuthorize("@pms.hasPermission('job_sys_job_shutdown_job')")
    @ApiOperation(value = "暂停全部定时任务")
    public R shutdownJobs() {
        // taskUtil.pauseJobs(scheduler);
        int count = this.sysJobService
            .count(new LambdaQueryWrapper<SysJob>().eq(SysJob::getJobStatus, JOB_STATUS_RUNNING.getType()));
        if (count <= 0) {
            return R.ok("无正在运行定时任务");
        } else {
            sysJobService.list().forEach((sysjob) -> {
                if (JOB_STATUS_RUNNING.getType().equals(sysjob.getJobStatus())) {
                    this.sysJobService.updateById(
                        SysJob.builder().jobId(sysjob.getJobId()).jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build());
                    taskUtil.pauseJob(sysjob, scheduler);
                }
            });
            // 更新定时任务状态条件，运行状态2更新为暂停状态2
            /*this.sysJobService.update(SysJob.builder()
                    .jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build(), new UpdateWrapper<SysJob>()
                    .lambda().eq(SysJob::getJobStatus, JOB_STATUS_RUNNING.getType()));*/
            return R.ok("暂停成功");
        }
    }

    /**
     * 启动全部定时任务
     *
     * @return
     */
    @SysLog("启动全部定时任务")
    @ResponseBody
    @PostMapping("/start-jobs")
    @PreAuthorize("@pms.hasPermission('job_sys_job_start_job')")
    @ApiOperation(value = "启动全部定时任务")
    public R startJobs() {
        // 更新定时任务状态条件，暂停状态3更新为运行状态2
        this.sysJobService.update(SysJob.builder().jobStatus(JOB_STATUS_RUNNING.getType()).build(),
            new UpdateWrapper<SysJob>().lambda().eq(SysJob::getJobStatus, JOB_STATUS_NOT_RUNNING.getType()));
        taskUtil.startJobs(scheduler);
        return R.ok();
    }

    /**
     * 刷新全部定时任务
     *
     * @return
     */
    @SysLog("刷新全部定时任务")
    @ResponseBody
    @PostMapping("/refresh-jobs")
    @PreAuthorize("@pms.hasPermission('job_sys_job_refresh_job')")
    @ApiOperation(value = "刷新全部定时任务")
    public R refreshJobs() {
        sysJobService.list().forEach((sysjob) -> {
            if (JOB_STATUS_RELEASE.getType().equals(sysjob.getJobStatus())
                || JOB_STATUS_DEL.getType().equals(sysjob.getJobStatus())) {
                taskUtil.removeJob(sysjob, scheduler);
            } else if (JOB_STATUS_RUNNING.getType().equals(sysjob.getJobStatus())
                || JOB_STATUS_NOT_RUNNING.getType().equals(sysjob.getJobStatus())) {
                taskUtil.addOrUpateJob(sysjob, scheduler);
            } else {
                taskUtil.removeJob(sysjob, scheduler);
            }
        });
        return R.ok();
    }

    /**
     * 启动定时任务
     *
     * @param jobId
     * @return
     */
    @SysLog("启动定时任务")
    @ResponseBody
    @PostMapping("/start-job/{id}")
    @PreAuthorize("@pms.hasPermission('job_sys_job_start_job')")
    @ApiOperation(value = "启动定时任务")
    public R startJob(@PathVariable("id") Integer jobId) {
        SysJob querySysJob = this.sysJobService.getById(jobId);
        if (querySysJob != null && JOB_LOG_STATUS_FAIL.getType().equals(querySysJob.getJobStatus())) {
            taskUtil.addOrUpateJob(querySysJob, scheduler);
        } else {
            taskUtil.resumeJob(querySysJob, scheduler);
        }
        // 更新定时任务状态条件，暂停状态3更新为运行状态2
        this.sysJobService.updateById(SysJob.builder().jobId(jobId).jobStatus(JOB_STATUS_RUNNING.getType()).build());
        return R.ok();
    }

    /**
     * 启动定时任务
     *
     * @param jobId
     * @return
     */
    @SysLog("立刻执行定时任务")
    @ResponseBody
    @PostMapping("/run-job/{id}")
    @PreAuthorize("@pms.hasPermission('job_sys_job_run_job')")
    @ApiOperation(value = "立刻执行定时任务")
    public R runJob(@PathVariable("id") Integer jobId) {
        SysJob querySysJob = this.sysJobService.getById(jobId);
        return TaskUtil.runOnce(scheduler, querySysJob) ? R.ok() : R.failed("执行失败，请重试");
    }

    /**
     * 暂停定时任务
     *
     * @return
     */
    @SysLog("暂停定时任务")
    @ResponseBody
    @PostMapping("/shutdown-job/{id}")
    @PreAuthorize("@pms.hasPermission('job_sys_job_shutdown_job')")
    @ApiOperation(value = "暂停定时任务")
    public R shutdownJob(@PathVariable("id") Integer id) {
        SysJob querySysJob = this.sysJobService.getById(id);
        // 更新定时任务状态条件，运行状态2更新为暂停状态3
        this.sysJobService.updateById(
            SysJob.builder().jobId(querySysJob.getJobId()).jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build());
        taskUtil.pauseJob(querySysJob, scheduler);
        return R.ok();
    }
}
